package models

import "gorm.io/gorm"

type Goods struct {
	gorm.Model
	Name  string  `json:"name"`
	Price float64 `json:"price"`
	Cate  string  `json:"cate"`
	Img   string  `json:"img"`
	Info  string  `json:"info"`
}

func CreateGoods(goods *Goods) error {
	return DB.Create(goods).Error
}

func UpdateGoods(goods *Goods) error {
	return DB.Save(goods).Error
}

func DeleteGoods(id uint) error {
	return DB.Delete(&Goods{}, id).Error
}

func GetGoodsByID(id uint) (*Goods, error) {
	var goods Goods
	err = DB.First(&goods, id).Error
	if err != nil {
		return nil, err
	}
	return &goods, nil
}

func GetAllGoods(name string, minPrice, maxPrice float64, page, size int) ([]Goods, int64, error) {
	var query *gorm.DB
	query = DB.Model(&Goods{})

	// 多条件搜索
	if name != "" {
		query = query.Where("name LIKE ?", "%"+name+"%")
	}
	if minPrice > 0 {
		query = query.Where("price >= ?", minPrice)
	}
	if maxPrice > 0 {
		query = query.Where("price <= ?", maxPrice)
	}

	// 计算总数
	var count int64
	if err = query.Count(&count).Error; err != nil {
		return nil, 0, err
	}

	// 计算偏移量
	offset := (page - 1) * size

	// 查询分页数据
	var goods []Goods
	if err = query.Order("price desc").Offset(offset).Limit(size).Find(&goods).Error; err != nil {
		return nil, 0, err
	}

	return goods, count, nil
}
